#include "fig_flyingpath.h"
#include "fig_enemy_pathcraft.h"
#include "fighter.h"

#include "num/crc32.h"

FIGFlyingPath&	FIGFlyingPath::Instance()
{
	static FIGFlyingPath	Inst;
	return Inst;


}


void	FIGFlyingPath::FlyingPath::AddPathPiece( float Rotation, float RotateSpeed, float Distance)
{
	FIGFlyingPath::PathPiece* pPathPiece = new FIGFlyingPath::PathPiece();

	pPathPiece->Distance = Distance;
	pPathPiece->TargetRotation = Rotation;
	pPathPiece->RotateSpeed = RotateSpeed;

	m_PathPieces.push_back(pPathPiece);
}


const FIGFlyingPath::PathInfo&			FIGFlyingPath::GetPosFromPath(
																		PATH_TYPE PType,
																		CraftInfo&	pCraftInfo,
																		float dt
																		)
{
		
	FIGFlyingPath::FlyingPath* pPath = GetPathByType(PType);
	
	
	m_PathInfo.Rotation = 0;
	m_PathInfo.m_IsDone = false;
	
	
	if(pPath && pCraftInfo.PathPieceIndex < (int) pPath->m_PathPieces.size() )
	{
		
		FIGFlyingPath::PathPiece* pPathPiece = pPath->m_PathPieces[pCraftInfo.PathPieceIndex];

		if(  pPathPiece->Distance > 0 )
		{
			
			if(pCraftInfo.DistantTravelled > pPathPiece->Distance)
			{
				
				pCraftInfo.PathPieceIndex++;
				pCraftInfo.DistantTravelled = 0;
			}
		}
		else if ( pPathPiece->Distance == 0)
		{
			float Target = pPathPiece->TargetRotation;
			float RotationDone = pCraftInfo.RotationDone;
			if(Target < 0)
				Target *= -1;
			if(RotationDone < 0)
				RotationDone *= -1;


			if ( RotationDone < Target)
			{
				m_PathInfo.Rotation = pPathPiece->RotateSpeed * dt * ( 1.0f / Fighter::Instance().GetScale());
				if(pPathPiece->TargetRotation < 0)
					m_PathInfo.Rotation *= -1;

				float Temp = pCraftInfo.RotationDone;
				pCraftInfo.RotationDone +=  m_PathInfo.Rotation;

				 if(RotationDone > Target)
				 {
					pCraftInfo.RotationDone = Target - Temp;
				 }
			}
			else
			{
				m_PathInfo.Rotation = 0;
				pCraftInfo.RotationDone = 0;
 				pCraftInfo.PathPieceIndex++;
				pCraftInfo.DistantTravelled = 0;
			}
		}
		
		
	}
	else
	{
		m_PathInfo.m_IsDone = true;
	}
	

	return m_PathInfo;
	
}


FIGFlyingPath::FlyingPath*		FIGFlyingPath::GetPathByType(FIGFlyingPath::PATH_TYPE PathType)
{

	FIGFlyingPath::FlyingPath* pPath = m_FlyingPaths[PathType];
	return pPath;
	

}

FIGFlyingPath::FlyingPath*		FIGFlyingPath::GetPath(FIGEnemyPathCraft* pCraft)
{

	FIGFlyingPath::FlyingPath* pPath = GetPathByType(pCraft->GetPathType());
	return pPath;
		
}

FIGFlyingPath::~FIGFlyingPath()
{
	for(int i = 0; i < PATH_COUNT; i++)
	{
		UTIL_SAFE_DELETE(m_FlyingPaths[i]);
	}
	
}



